package com.adong.crowd.filter;

import com.adong.crowd.constant.AccessPathResources;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 路径请求的过滤器
 */
@Controller
public class CrowdAccessFilter extends ZuulFilter {
    @Override
    public boolean shouldFilter() {
        // 获取RequestContext对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 获取RequestContext获取当前请求对象
        HttpServletRequest request = requestContext.getRequest();
        // 获取ServletPath的值
        String servletPath = request.getServletPath();
        // 根据ServletPath是否为放行请求
        boolean result = AccessPathResources.PASS_RES_SET.contains(servletPath);
        if (result) {
            // 当前请求直接放行,返回flase;
            return false;
        }
        // 判断是否为静态资源
        boolean contains = AccessPathResources.judgeCurrentServletPathWetherStaticResource(servletPath);
        if (contains) {
            // 静态资源直接放行
            return false;
        }
        // 不能放行,进入run进行判断
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取RequestContext对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 获取RequestContext获取当前请求对象
        HttpServletRequest request = requestContext.getRequest();
        HttpSession session = request.getSession();

        // 判断域中是否有loginMember对象存在
        Object loginMember = session.getAttribute("loginMember");

        if (loginMember == null) {
            // 没有登录
            HttpServletResponse response = requestContext.getResponse();
            session.setAttribute("message", "请登录以后访问");
            try {
                response.sendRedirect("/auth/member/to/login/page");
            } catch (IOException e) {

            }
        }
        return null;
    }

    @Override
    public String filterType() {
        // 在目标微服务前执行过滤
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }


}
